package servlet;

import service.CommentService;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    private CommentService commentService = new CommentService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 检查登录状态
        Integer userId = SessionUtils.getCurrentUserId(request);
        if (userId == null) {
            response.sendRedirect("login.html");
            return;
        }

        // 获取参数
        String content = request.getParameter("content");
        String articleIdStr = request.getParameter("articleId");

        // 参数校验
        if (content == null || content.trim().isEmpty()) {
            request.getSession().setAttribute("error", "评论内容不能为空");
            response.sendRedirect("articleDetail?id=" + articleIdStr);
            return;
        }

        if (articleIdStr == null || articleIdStr.trim().isEmpty()) {
            request.getSession().setAttribute("error", "文章ID不能为空");
            response.sendRedirect("index.jsp");
            return;
        }

        try {
            int articleId = Integer.parseInt(articleIdStr);

            // 提交评论
            boolean success = commentService.submitComment(content.trim(), articleId, userId);

            // 处理结果
            if (success) {
                request.getSession().setAttribute("success", "评论发表成功！");
            } else {
                request.getSession().setAttribute("error", "评论提交失败，请检查内容");
            }

            response.sendRedirect("articleDetail?id=" + articleId);

        } catch (NumberFormatException e) {
            request.getSession().setAttribute("error", "文章ID格式错误");
            response.sendRedirect("index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("error", "系统错误，请稍后重试");
            response.sendRedirect("articleDetail?id=" + articleIdStr);
        }
    }
}